using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using AdminSG3L.Applicaticn.ServicesInterface;
using AdminSG3L.Applicaticn.Dtos;

namespace AdminSG3L.Api.Controllers;

/// <summary>
/// 分析统计控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class AnalyticsController(IAnalyticsService analyticsService) : ControllerBase
{
    private readonly IAnalyticsService _analyticsService = analyticsService;

    /// <summary>
    /// 获取仪表盘数据
    /// </summary>
    [HttpGet("dashboard")]
    public async Task<IActionResult> GetDashboardData([FromQuery] string timeRange = "7d")
    {
        var result = await _analyticsService.GetDashboardDataAsync(timeRange);
        return Ok(result);
    }

    /// <summary>
    /// 获取访问统计
    /// </summary>
    [HttpGet("visits")]
    public async Task<IActionResult> GetVisitStats([FromQuery] VisitStatsQueryDto query)
    {
        var result = await _analyticsService.GetVisitStatsAsync(query);
        return Ok(result);
    }

    /// <summary>
    /// 获取用户行为分析
    /// </summary>
    [HttpGet("users/{userId}/behavior")]
    public async Task<IActionResult> GetUserBehavior(string userId, [FromQuery] UserBehaviorQueryDto query)
    {
        var result = await _analyticsService.GetUserBehaviorAsync(userId, query);
        return Ok(result);
    }

    /// <summary>
    /// 获取页面访问统计
    /// </summary>
    [HttpGet("pages")]
    public async Task<IActionResult> GetPageStats([FromQuery] VisitStatsQueryDto query)
    {
        var result = await _analyticsService.GetPageStatsAsync(query);
        return Ok(result);
    }

    /// <summary>
    /// 获取实时数据
    /// </summary>
    [HttpGet("realtime")]
    public async Task<IActionResult> GetRealTimeData()
    {
        var result = await _analyticsService.GetRealTimeDataAsync();
        return Ok(result);
    }

    /// <summary>
    /// 获取转化漏斗数据
    /// </summary>
    [HttpGet("funnels/{funnelId}")]
    public async Task<IActionResult> GetFunnelData(Guid funnelId, [FromQuery] VisitStatsQueryDto query)
    {
        var result = await _analyticsService.GetFunnelDataAsync(funnelId, query);
        return Ok(result);
    }

    /// <summary>
    /// 获取留存分析
    /// </summary>
    [HttpGet("retention")]
    public async Task<IActionResult> GetRetentionAnalysis([FromQuery] RetentionQueryDto query)
    {
        var result = await _analyticsService.GetRetentionAnalysisAsync(query);
        return Ok(result);
    }

    /// <summary>
    /// 获取用户画像数据
    /// </summary>
    [HttpGet("user-portrait")]
    public async Task<IActionResult> GetUserPortrait([FromQuery] UserPortraitQueryDto query)
    {
        var result = await _analyticsService.GetUserPortraitAsync(query);
        return Ok(result);
    }

    /// <summary>
    /// 获取热力图数据
    /// </summary>
    [HttpGet("heatmap")]
    public async Task<IActionResult> GetHeatmapData([FromQuery] HeatmapQueryDto query)
    {
        var result = await _analyticsService.GetHeatmapDataAsync(query);
        return Ok(result);
    }

    /// <summary>
    /// 获取事件统计
    /// </summary>
    [HttpGet("events")]
    public async Task<IActionResult> GetEventStats([FromQuery] EventStatsQueryDto query)
    {
        var result = await _analyticsService.GetEventStatsAsync(query);
        return Ok(result);
    }

    /// <summary>
    /// 记录用户行为事件
    /// </summary>
    [HttpPost("events")]
    [AllowAnonymous] // 通常事件追踪不需要认证
    public async Task<IActionResult> TrackEvent([FromBody] UserBehaviorDto eventData)
    {
        var result = await _analyticsService.TrackEventAsync(eventData);
        return Ok(result);
    }

    /// <summary>
    /// 批量记录用户行为事件
    /// </summary>
    [HttpPost("events/batch")]
    [AllowAnonymous]
    public async Task<IActionResult> BatchTrackEvents([FromBody] List<UserBehaviorDto> events)
    {
        var result = await _analyticsService.BatchTrackEventsAsync(events);
        return Ok(result);
    }

    /// <summary>
    /// 创建自定义报表
    /// </summary>
    [HttpPost("reports")]
    public async Task<IActionResult> CreateCustomReport([FromBody] CustomReportConfigDto reportConfig)
    {
        var result = await _analyticsService.CreateCustomReportAsync(reportConfig);
        return Ok(result);
    }

    /// <summary>
    /// 获取报表列表
    /// </summary>
    [HttpGet("reports")]
    public async Task<IActionResult> GetReports([FromQuery] int page = 1, [FromQuery] int pageSize = 20)
    {
        var result = await _analyticsService.GetReportsAsync(page, pageSize);
        return Ok(result);
    }

    /// <summary>
    /// 获取报表详情
    /// </summary>
    [HttpGet("reports/{reportId}")]
    public async Task<IActionResult> GetReportById(Guid reportId)
    {
        var result = await _analyticsService.GetReportByIdAsync(reportId);
        if (result.Code == 404)
            return NotFound(result);
        return Ok(result);
    }

    /// <summary>
    /// 更新报表
    /// </summary>
    [HttpPut("reports/{reportId}")]
    public async Task<IActionResult> UpdateReport(Guid reportId, [FromBody] CustomReportConfigDto reportConfig)
    {
        var result = await _analyticsService.UpdateReportAsync(reportId, reportConfig);
        if (result.Code == 404)
            return NotFound(result);
        return Ok(result);
    }

    /// <summary>
    /// 删除报表
    /// </summary>
    [HttpDelete("reports/{reportId}")]
    public async Task<IActionResult> DeleteReport(Guid reportId)
    {
        var result = await _analyticsService.DeleteReportAsync(reportId);
        return Ok(result);
    }

    /// <summary>
    /// 导出报表
    /// </summary>
    [HttpGet("reports/{reportId}/export")]
    public async Task<IActionResult> ExportReport(Guid reportId, [FromQuery] string format = "excel")
    {
        var result = await _analyticsService.ExportReportAsync(reportId, format);
        if (result.Code != 200 || result.Data == null)
        {
            return BadRequest(result);
        }

        var fileName = $"report_{reportId}_{DateTime.Now:yyyyMMdd_HHmmss}.{format}";
        var contentType = format.ToLower() switch
        {
            "excel" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "csv" => "text/csv",
            "pdf" => "application/pdf",
            _ => "application/json"
        };

        return File(result.Data, contentType, fileName);
    }

    /// <summary>
    /// 获取数据对比分析
    /// </summary>
    [HttpGet("comparison")]
    public async Task<IActionResult> GetComparisonData([FromQuery] ComparisonQueryDto query)
    {
        var result = await _analyticsService.GetComparisonDataAsync(query);
        return Ok(result);
    }

    /// <summary>
    /// 获取趋势分析
    /// </summary>
    [HttpGet("trends")]
    public async Task<IActionResult> GetTrendAnalysis([FromQuery] TrendAnalysisQueryDto query)
    {
        var result = await _analyticsService.GetTrendAnalysisAsync(query);
        return Ok(result);
    }

    /// <summary>
    /// 获取异常检测数据
    /// </summary>
    [HttpGet("anomalies")]
    public async Task<IActionResult> GetAnomalyDetection([FromQuery] AnomalyDetectionQueryDto query)
    {
        var result = await _analyticsService.GetAnomalyDetectionAsync(query);
        return Ok(result);
    }

    /// <summary>
    /// 获取预测分析
    /// </summary>
    [HttpGet("predictions")]
    public async Task<IActionResult> GetPredictionData([FromQuery] PredictionQueryDto query)
    {
        var result = await _analyticsService.GetPredictionDataAsync(query);
        return Ok(result);
    }

    /// <summary>
    /// 创建数据提醒
    /// </summary>
    [HttpPost("alerts")]
    public async Task<IActionResult> CreateAlert([FromBody] AlertConfigDto alertConfig)
    {
        var result = await _analyticsService.CreateAlertAsync(alertConfig);
        return Ok(result);
    }

    /// <summary>
    /// 获取提醒列表
    /// </summary>
    [HttpGet("alerts")]
    public async Task<IActionResult> GetAlerts()
    {
        var result = await _analyticsService.GetAlertsAsync();
        return Ok(result);
    }

    /// <summary>
    /// 更新提醒状态
    /// </summary>
    [HttpPut("alerts/{alertId}/status")]
    public async Task<IActionResult> UpdateAlertStatus(Guid alertId, [FromBody] UpdateAlertStatusDto dto)
    {
        var result = await _analyticsService.UpdateAlertStatusAsync(alertId, dto.Status);
        return Ok(result);
    }

    /// <summary>
    /// 删除提醒
    /// </summary>
    [HttpDelete("alerts/{alertId}")]
    public async Task<IActionResult> DeleteAlert(Guid alertId)
    {
        var result = await _analyticsService.DeleteAlertAsync(alertId);
        return Ok(result);
    }

    /// <summary>
    /// 获取系统性能指标
    /// </summary>
    [HttpGet("system-metrics")]
    public async Task<IActionResult> GetSystemMetrics()
    {
        var result = await _analyticsService.GetSystemMetricsAsync();
        return Ok(result);
    }

    /// <summary>
    /// 获取数据统计概览
    /// </summary>
    [HttpGet("overview")]
    public async Task<IActionResult> GetDataOverview(
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null)
    {
        var result = await _analyticsService.GetDataOverviewAsync(startDate, endDate);
        return Ok(result);
    }

    /// <summary>
    /// 计算业务指标
    /// </summary>
    [HttpPost("business-metrics")]
    public async Task<IActionResult> CalculateBusinessMetrics(
        [FromBody] BusinessMetricsQueryDto dto)
    {
        var result = await _analyticsService.CalculateBusinessMetricsAsync(dto.Metrics, dto.StartDate, dto.EndDate);
        return Ok(result);
    }

    /// <summary>
    /// 获取用户分群数据
    /// </summary>
    [HttpGet("user-segments")]
    public async Task<IActionResult> GetUserSegments([FromQuery] UserPortraitQueryDto query)
    {
        var result = await _analyticsService.GetUserSegmentsAsync(query);
        return Ok(result);
    }

    /// <summary>
    /// 获取转化路径分析
    /// </summary>
    [HttpGet("conversion-paths")]
    public async Task<IActionResult> GetConversionPaths(
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null)
    {
        var result = await _analyticsService.GetConversionPathsAsync(startDate, endDate);
        return Ok(result);
    }

    /// <summary>
    /// 获取用户生命周期分析
    /// </summary>
    [HttpGet("user-lifecycle")]
    public async Task<IActionResult> GetUserLifecycle(
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null)
    {
        var result = await _analyticsService.GetUserLifecycleAsync(startDate, endDate);
        return Ok(result);
    }

    /// <summary>
    /// 获取归因分析
    /// </summary>
    [HttpGet("attribution")]
    public async Task<IActionResult> GetAttributionAnalysis(
        [FromQuery] string conversionEvent,
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null)
    {
        var result = await _analyticsService.GetAttributionAnalysisAsync(conversionEvent, startDate, endDate);
        return Ok(result);
    }

    /// <summary>
    /// 获取页面性能分析
    /// </summary>
    [HttpGet("page-performance")]
    public async Task<IActionResult> GetPagePerformance(
        [FromQuery] string? pageUrl = null,
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null)
    {
        var result = await _analyticsService.GetPagePerformanceAsync(pageUrl, startDate, endDate);
        return Ok(result);
    }

    /// <summary>
    /// 获取错误跟踪数据
    /// </summary>
    [HttpGet("error-tracking")]
    public async Task<IActionResult> GetErrorTracking(
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null)
    {
        var result = await _analyticsService.GetErrorTrackingAsync(startDate, endDate);
        return Ok(result);
    }

    /// <summary>
    /// 生成洞察报告
    /// </summary>
    [HttpGet("insights")]
    public async Task<IActionResult> GenerateInsights(
        [FromQuery] string reportType,
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null)
    {
        var result = await _analyticsService.GenerateInsightsAsync(reportType, startDate, endDate);
        return Ok(result);
    }

    /// <summary>
    /// 获取A/B测试结果
    /// </summary>
    [HttpGet("ab-tests")]
    public async Task<IActionResult> GetAbTestResults([FromQuery] string? testId = null)
    {
        var result = await _analyticsService.GetAbTestResultsAsync(testId);
        return Ok(result);
    }

    /// <summary>
    /// 清理过期分析数据
    /// </summary>
    [HttpPost("cleanup")]
    [Authorize(Roles = "Administrator")]
    public async Task<IActionResult> CleanupExpiredData([FromQuery] int keepDays = 365)
    {
        var result = await _analyticsService.CleanupExpiredDataAsync(keepDays);
        return Ok(result);
    }

    /// <summary>
    /// 导出分析数据
    /// </summary>
    [HttpGet("export")]
    public async Task<IActionResult> ExportAnalyticsData(
        [FromQuery] string dataType,
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null,
        [FromQuery] string format = "excel")
    {
        var result = await _analyticsService.ExportAnalyticsDataAsync(dataType, startDate, endDate, format);
        if (result.Code != 200 || result.Data == null)
        {
            return BadRequest(result);
        }

        var fileName = $"analytics_{dataType}_{DateTime.Now:yyyyMMdd_HHmmss}.{format}";
        var contentType = format.ToLower() switch
        {
            "excel" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "csv" => "text/csv",
            "pdf" => "application/pdf",
            _ => "application/json"
        };

        return File(result.Data, contentType, fileName);
    }

    /// <summary>
    /// 获取数据质量报告
    /// </summary>
    [HttpGet("data-quality")]
    public async Task<IActionResult> GetDataQualityReport(
        [FromQuery] DateTime? startDate = null,
        [FromQuery] DateTime? endDate = null)
    {
        var result = await _analyticsService.GetDataQualityReportAsync(startDate, endDate);
        return Ok(result);
    }

    /// <summary>
    /// 健康检查 - 检查分析系统状态
    /// </summary>
    [HttpGet("health")]
    [AllowAnonymous]
    public async Task<IActionResult> HealthCheck()
    {
        try
        {
            var overview = await _analyticsService.GetDataOverviewAsync();
            dynamic overviewResult = overview;
            
            var health = new
            {
                Status = overviewResult.Code == 200 ? "Healthy" : "Unhealthy",
                Service = "分析统计服务",
                Timestamp = DateTime.UtcNow,
                Details = new
                {
                    DatabaseConnection = overviewResult.Code == 200 ? "Connected" : "Failed",
                    DataAccess = overviewResult.Code == 200 ? "Accessible" : "Failed"
                }
            };

            return overviewResult.Code == 200 ? Ok(health) : StatusCode(503, health);
        }
        catch (Exception ex)
        {
            var health = new
            {
                Status = "Unhealthy",
                Service = "分析统计服务",
                Timestamp = DateTime.UtcNow,
                Error = ex.Message
            };
            return StatusCode(503, health);
        }
    }
}

/// <summary>
/// 更新提醒状态请求DTO
/// </summary>
public class UpdateAlertStatusDto
{
    public required string Status { get; set; }
}

/// <summary>
/// 业务指标查询DTO
/// </summary>
public class BusinessMetricsQueryDto
{
    public List<string> Metrics { get; set; } = new();
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
}
